<template>
  <div class="message-list">
    <div class="message-hd">
      <h1>{{ friendNickname }}</h1>
      <router-link to='/chat/list' class="arrow-wrap">
        <i class="arrow-back"></i>
      </router-link>
      </div>
      <div id="message-box" :style="'height:'+fullHeight+'px;'">
        <ul id="message-list" ref="messageBox">
          <li v-for="list in msgList">
            <p class="time"><span>{{ new Date(list.create_time).getFullYear()+"-"+(new Date(list.create_time).getMonth()+1)+"-"+new Date(list.create_time).getDate()+" "+new Date(list.create_time).getHours()+":"+new Date(list.create_time).getMinutes() }}</span></p>
            <div :class="list.send_user_id == userId?'main self':'main'">
              <img class="photo" :src="list.send_user_id == userId?userHeadImg:friendHeadImg">
              <div class="text">{{ list.content }}</div>
            </div>
          </li>
      </ul>
    </div>
    <div class="message-input">
      <input type="text" class="message-text" ref="message_text" v-model="txtMsgSend">
      <button type="button" class="message-btn" @click="sendMsg">发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "chatWin",
  data() {
    return {
      msgList:[],
      txtMsgSend:"",
      userId:this.getCookie('id'),
      userHeadImg:this.getCookie('head_img'),
      friendId:this.$route.query.friendId,
      friendNickname:this.$route.query.friendNickname,
      friendHeadImg:this.$route.query.friendHeadImg,
      websockLink:'',
      fullHeight: document.documentElement.clientHeight
    }
  },
  created() {
    this.initWebSocket()
    if(JSON.stringify(this.$route.query)=='{}'){
      this.$router.push('/chat/list')
    }
    else{
      this.$axios.get('/message/user/list',{params:{token:this.getCookie('userToken'),user_id:this.getCookie('id'),friend_id:this.$route.query.friendId}}).then(reponse=>{
        let res=reponse.data;
        if(res.state===200){
          this.msgList=res.data;
        }
        else if(res.state===500){
          alert(res.msg);
          this.$router.push('/login')
        }
        else{
          alert(res.msg);
        }
      })
    }
  },
  mounted() {
    this.get_bodyHeight();
    this.scrollToBottom();

  },
  updated:function(){
    this.scrollToBottom();
  },
  destroyed() {
    this.websocketclose()
  },
  methods:{
    threadPoxi(){  // 实际调用的方法
        //参数
        const agentData = "mymessage";
        //若是ws开启状态
        if (this.websock.readyState === this.websock.OPEN) {
            this.websocketsend(agentData)
        }
        // 若是 正在开启状态，则等待300毫秒
        else if (this.websock.readyState === this.websock.CONNECTING) {
            let that = this;//保存当前对象this
            setTimeout(function () {
                that.websocketsend(agentData)
            }, 300);
        }
        // 若未开启 ，则等待500毫秒
        else {
            this.initWebSocket();
            let that = this;//保存当前对象this
            setTimeout(function () {
                that.websocketsend(agentData)
            }, 500);
        }
    },
    initWebSocket() {
      const websockLink = global.origin.replace('http','ws').replace('https','ws')+'/socket.io/?user_id='+ this.getCookie('id')
      this.websock = new WebSocket(websockLink)
      this.websock.onopen = this.websocketonopen
      if (this.websock.readyState == WebSocket.OPEN) this.websock.onopen();
       window.s = this.websock;
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketclose
    },
    websocketsend(agentData){//数据发送
        this.websock.send(agentData);
    },
    websocketonopen() {
      console.log('WebSocket连接成功')
      //发送字符:
      this.websocketsend(JSON.stringify({
        'user_id': this.getCookie('id'),
        'type':'client'
      }));
    },
    websocketonerror(e) {
      console.log('WebSocket连接发生错误')
      console.log({
              title: '错误',
              message: e,
              type: 'error',
              duration: 0
            })
    },
    websocketonmessage(msg) {
      console.log('WebSocket信息通知')
      if('data' in msg){
        let returnData = JSON.parse(msg.data)
        if(returnData.data.type=='sendMessage'){
          let date=new Date();
          let nowTime=1900+date.getYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+" "+date.getHours()+":"+date.getMinutes();
          this.msgList.push({
            content:returnData.data.message,
            send_user_id:this.user_id,
            create_time:nowTime
          })
        }
      }
    },
    websocketclose(e) {
      console.log('关闭WebSocket连接')
    },
    get_bodyHeight () {//动态获取浏览器高度
      const that = this
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight
          that.fullHeight = window.fullHeight
        })()
      }
    },
    scrollToBottom(){
      this.$nextTick(function(){
        var box = this.$el.querySelector('#message-box');
        box.scrollTop = box.scrollHeight
        window.scrollTo(0, box.scrollHeight);
      })
    },
      sendMsg(){
      if(this.txtMsgSend!==""){
        let date=new Date();
        let nowTime=1900+date.getYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+" "+date.getHours()+":"+date.getMinutes();
        this.msgList.push({
          content:this.txtMsgSend,
          send_user_id:this.userId,
          create_time:nowTime
        });
        var data={user_id:parseInt(this.userId),friend_id:parseInt(this.friendId),content:this.txtMsgSend,token:this.getCookie('userToken')};
        this.$axios.post('/message/message',data);
        //this.socket_io.emit('sendMessage',data);
        //sockeio
        this.websocketsend(JSON.stringify({
          'friend_id': parseInt(this.friendId),
          'type':'sendMessage',
          'message':this.txtMsgSend
        }));
        this.txtMsgSend="";
      }
    }
  }
}
</script>

<style scoped>
  @import "../../static/css/chatWin.css";
</style>
